<?php
/*内部转账*/
require_once("../config/dbconn.php");

$act = isset($_POST['act']) ? $_POST['act'] : 'zhuanzhang_list';#方法
$username = isset($_POST['username']) ? trim($_POST['username']) : '';

#允许访问的方法---在每天结算时
$allow_act = array('caiwulist');
$nowtime = time();//当前时间

$js_starttime = strtotime(date('Y-m-d').' 00:00:00');
$js_endtime = strtotime(date('Y-m-d').' 06:00:00');
if($nowtime >=$js_starttime && $nowtime < $js_endtime && !in_array($act, $allow_act)){
    returnJson(0,'系统结算中，转账功能暂时关闭。');
}

//内部转账 默认页数据
if ($act == 'zhuanzhang_list') {
     returnJson(0,'系统升级，转账功能暂时关闭。');
	zhuanzhang($username);
}

/*提交数据后的内部转账*/
if($act == 'apply'){
     returnJson(0,'系统升级，转账功能暂时关闭。');

//    dump($_POST);
    $type = isset($_POST['type']) ? intval($_POST['type']) : 1;#内部互转类型 1释放转交易 2智能转交易 3算力转交易 5 交易转资产
	$num =  isset($_POST['num']) ? intval($_POST['num']) : '';	#转账的TXL数量
	$code = isset($_POST['code']) ? intval($_POST['code']) : '';	#手机验证码
	apply_zhuanzhang($username,$type,$num,$code);
}

if($act == 'caiwulist'){
    caiwu_list($username);
}

if($act == 'outAccount'){
     returnJson(0,'系统升级，转账功能暂时关闭。');

    $code = isset($_POST['code']) ? $_POST['code'] : '';    #手机验证码
    $money =  isset($_POST['num']) ? $_POST['num'] : 0;  #转账的TXL数量
    $paypwd = isset($_POST['paypwd']) ? $_POST['paypwd'] : '';    #交易密码
    $type = isset($_POST['type']) ? $_POST['type'] : 1;#外部互转类型 1交易转资产
    TransferAccounts($username ,$code ,$money ,$paypwd ,$type );
}

function zhuanzhang($username){
     returnJson(0,'系统升级，转账功能暂时关闭。');

	global $db,$db_prefix,$glo_transfer_ratio;
	//获取该会员释放钱包、智能钱包、算力钱包,交易钱包余额
	$userinfo = $db->get_one("select id,username,mobile,sfprice,znprice,slprice,jyprice from {$db_prefix}users where username='".$username."'");
	$userinfo['transfer_ratio']= $glo_transfer_ratio;
	returnJson('1','请求成功',$userinfo);
}

function apply_zhuanzhang($username='',$type='',$num='',$code=''){
     returnJson(0,'系统升级，转账功能暂时关闭。');

	global $db,$db_prefix,$glo_transfer_ratio,$curtime;
    // if(empty($username)) returnJson(0,'用户信息不能为空');
    if(empty($type)) returnJson(0,'转账方式不存在');
    if(empty($num)) returnJson(0,'转账数量不能为空');
    if(empty($code)) returnJson(0,'验证码不能为空');
    if($num<0) returnJson(0,'请输入正确的转账数量');
    #1.验证用户登录是否失效
    $loginUser = isset($_SESSION['user']) ? $_SESSION['user'] : null;
    if(empty($loginUser) || $loginUser['id'] <= 0)  returnJson(0,'用户登录状态失效，请重新登录');
    //验证会员合法性
   $userinfo =  $db->get_one("select id,username,mobile,sfprice,znprice,slprice,jyprice,ft_isend from {$db_prefix}users where id={$loginUser['id']}");
    if(!empty($userinfo)){

        // if($userinfo['ft_isend'] ==1){
        //     returnJson(0,"超出累计收入上限，暂不可使用此功能");
        // }
        $mobile = $userinfo['mobile'];
        $userid = $userinfo['id'];
        if(!empty($mobile)){
            //短信验证
           checkcode($mobile,$code);
        }else{
            returnJson(0,'用户信息不完整');
        }
        switch ($type) {
            case '1':
                $balance = $userinfo['sfprice'];
                $account = 'sfprice';
                $e_ptype = 2;
                $e_type = 1;
                break;
            case '2':
                $balance = $userinfo['znprice'];
                $account = 'znprice';
                $e_ptype = 3;
                $e_type = 4;
                break;
            case '3':
                $balance = $userinfo['slprice'];
                $account = 'slprice';
                $e_ptype = 4;
                $e_type = 5;
                break;
            case '5':
                $balance = $userinfo['jyprice'];
                $account = 'jyprice';
                $e_ptype = 5;
                $e_type = 14;
                break;
            default:
                break;
        }
        if($num >$balance){
            returnJson(0,'账户余额不足');
        }
        //如果转账操作是交易->资产，不扣税
        $tax_money =0;
        if($account != 'jyprice' && $e_type != 14 ){
            $tax_money = $num*($glo_transfer_ratio/100);    //税
        }
            //实际到帐金额
            $real_money = $num -$tax_money;

        $db->query('start transaction');#开启事物
        try{
            //
            if($account != 'jyprice' && $e_type != 14){   
                $sql = "update {$db_prefix}users set {$account}={$account}-{$num},jyprice=jyprice+{$real_money} where id='".$userid."'";
            }elseif($account == 'jyprice' && $e_type == 14){
                returnJson(0,'数据异常');
                $sql = "update {$db_prefix}users set {$account}={$account}-{$num},price=price+{$real_money},ljprice=ljprice+{$real_money},ft_times=ft_times+1,ft_isend=0,ft_number={$real_money} where id='".$userid."'";

            }
           $row = $db->query($sql);
            if(!$row){
                throw new Exception('转账失败');
            }
            if($account != 'jyprice' && $e_type != 14 ){
                //交易钱包财务记录
                $e_userid = $userid;
                $e_price = $real_money;
                $e_addtime = $curtime;
                $e_memo = "内部转账，转入TXL：" . $real_money;
                hyepricejl($e_userid, $e_price, $e_type, 5, $e_addtime, $e_memo);

                //转出钱包财务记录
                $e_userid = $userid;
                $e_price = -$num;
                $e_type = 4;
                $e_addtime = $curtime;
                $e_memo = "内部转账，转出TXL：" . $num;
                hyepricejl($e_userid, $e_price, $e_type, $e_ptype, $e_addtime, $e_memo);

                //记录税
                 $taxsql = "update {$db_prefix}users set jyprice=jyprice+{$tax_money} where username='TXL0001'";
               $taxrow = $db->query($taxsql);
                if(!$taxrow){
                    throw new Exception('税记录失败');
                }
                 //转出钱包财务记录
                $e_userid = '2235';
                $e_price = $tax_money;
                $e_addtime = $curtime;
                $e_memo = $username."内部转账，转入TXL：" . $real_money.",扣除税：".$tax_money;
                hyepricejl($e_userid, $e_price, 10, 5, $e_addtime, $e_memo);
            }else{
                //交易钱包转出记录
                $e_userid = $userid;
                $e_price = -$num;
                $e_type = 14;
                $e_addtime = $curtime;
                $e_memo = "复投，转出TXL：" . $num;
                hyepricejl($e_userid, $e_price, $e_type,5, $e_addtime, $e_memo);
                //资产钱包转入记录
                $e_userid = $userid;
                $e_price = $num;
                $e_type = 6;
                $e_addtime = $curtime;
                $e_memo = "复投，转入TXL：" . $num;
                hyepricejl($e_userid, $e_price, $e_type,1, $e_addtime, $e_memo);
            }
            
            $db->query('commit');#提交
            returnJson(1,'转账成功');
        }catch(Exception $e){
            $db->query('rollback');#回滚
            returnJson(0,$e->errorMessage());
        }

    }else{
        returnJson(0,'该会员不存在，请重新登录');
    }
}

function caiwu_list($username){
    global $db,$db_prefix,$hypricetypeary,$hypriceary,$hysfpriceary,$hyznpriceary,$hyslpriceary,$hyjypriceary,$hygwpriceary,$hydjpriceary;
    //查询该会员
    $sql ="select id,username from {$db_prefix}users where username = '".$username."'";
    $userinfo = $db->get_one($sql);
    if(empty($userinfo)){
        returnJson(0,'该会员不存在');
    }
    $sql ="select c.id,c.userid,c.price,c.type,c.ptype,c.addtime from {$db_prefix}caiwu as c where c.userid ={$userinfo['id']} and type!=2 and type !=3 order by c.addtime desc ";
    $caiwulist = $db->get_all($sql);
    if(empty($caiwulist)){
        returnJson(2,'您无任何记录信息');
    }

    foreach ($caiwulist as $k=>$v){
        switch ($v['ptype']){
            case '1':
                $caiwulist[$k]['type'] =$hypriceary[$v['type']];
                break;
            case '2':
                $caiwulist[$k]['type'] =$hysfpriceary[$v['type']];
                break;
            case '3':
                $caiwulist[$k]['type'] =$hyznpriceary[$v['type']];
                break;
            case '4':
                $caiwulist[$k]['type'] =$hyslpriceary[$v['type']];

                break;
            case '5':
                $caiwulist[$k]['type'] =$hyjypriceary[$v['type']];

                break;
            case '6':
                $caiwulist[$k]['type'] =$hygwpriceary[$v['type']];

                break;
            case '7':
                $caiwulist[$k]['type'] =$hydjpriceary[$v['type']];

                break;
        }
        $caiwulist[$k]['ptype'] =$hypricetypeary[$v['ptype']];
    }
    returnJson(1,'获取成功',$caiwulist);
}



/**
 * 会员转账接口 -- 由A会员的交易钱包转出到B会员的资产钱包
 * @param string $to_username 收款人编号
 * @param string $code     转出人手机验证码
 * @param string $paypwd   支付密码
 * @param string $money    转出金额
 * @param  int  $type      转账类型
 */
function TransferAccounts($to_username = '',$code = '',$money = 0,$paypwd = '',$type = 1){
     returnJson(0,'系统升级，转账功能暂时关闭。');
    
    global $db,$db_prefix,$curtime;
    #引入配置文件
    if(file_exists('../txljsadmin/transfer_setting_config.php')){
        include '../txljsadmin/transfer_setting_config.php';
    }
    if($transfer_setting['is_open'] != 1) returnJson(0,'系统内部转账已经关闭');

    #1.验证用户登录是否失效
    $loginUser = isset($_SESSION['user']) ? $_SESSION['user'] : null;
    if(empty($loginUser) || $loginUser['id'] <= 0)  returnJson(0,'用户登录状态失效，请重新登录');
    $allow_type = array(1);
    #2.验证参数
    $to_username = txl_trim($to_username);
    $code = txl_trim($code);
    $money = doubleval($money);
    $paypwd = txl_trim($paypwd);
    $type = intval($type);
    if(empty($to_username)) returnJson(0,'请填写收款人编号');
    if($money <= 0) returnJson(0,'转出数量需大于0');
    if(empty($code)) returnJson(0,'短信验证码不能为空');
    // if(empty($paypwd)) returnJson(0,'支付密码不能为空');
    if(!in_array($type, $allow_type)) returnJson(0,'请选择转出钱包类型');
    #3.查看转账人与收款人信息是否存在
    $from_users = $db->get_one("select * from {$db_prefix}users where id = {$loginUser['id']}");
    if(empty($from_users)) returnJson(0,'用户登录状态失效，请重新登录');
    if($from_users['islock'] == 1) returnJson(0,'您的账户已被冻结，转账失败');
    // if($from_users['ft_isend'] == 1) returnJson(0,'您的账户累计收入超出上限，暂不可使用此功能');
    $to_users = $db->get_one("select * from {$db_prefix}users where username = '{$to_username}'");
    if(empty($to_users)) returnJson(0,'收款人不存在，转账失败');
    if($from_users['id'] == $to_users['id']) returnJson(0,'抱歉您不能给自己转账');
    // if($to_users['ft_isend'] == 1) returnJson(0,'抱歉,对方累计收益超出上限，暂不可使用此功能');
    #限制用户
    // if(strtoupper($to_username) != 'FXY2409') returnJson(0,'功能正在努力开发中...'.$to_username);
    
    #白名单
    if(!empty($transfer_setting['allow_users'])){

        $allow_user_arr = explode(',', $transfer_setting['allow_users']);
        if(!in_array(strtoupper($from_users['username']), $allow_user_arr)) returnJson(0,'系统内部转账只限部分用户使用');
    } 
    #黑名单
    if(!empty($transfer_setting['blacklist'])){

        $black_list_arr = explode(',', $transfer_setting['blacklist']);
        if(in_array(strtoupper($from_users['username']), $black_list_arr)) returnJson(0,'系统内部转账只限部分用户使用');
    }
    #验证短信验证码
    checkcode($loginUser['mobile'],$code);

    #4.验证用户资金是否充足、支付密码是否正确
    if($from_users['jyprice'] < $money) returnJson(0,'钱包可用余额不足，转账失败');
    // if(authcode($from_users['pwd1']) != $paypwd) returnJson(0,'交易密码验证失败，请重试');
    #5.开启事物
    $db->query('start transaction');#开启事物
    try{
        #插入记录
        $insert_arr = array(
            'from_userid' => $from_users['id'],
            'from_username' => $from_users['username'],
            'to_userid' => $to_users['id'],
            'to_username' => $to_users['username'],
            'type' => $type,
            'money' => $money,
            'add_time' => $curtime,
            'log_text' => "{$from_users['username']}从交易钱包转出:{$money}到{$to_users['username']}的资产钱包"
        );
        $db->insert("{$db_prefix}transfer_account",$insert_arr);
        $insert_id=$db->insert_id();
        if(!$insert_id){
            throw new Exception("转账失败");            
        }
        #更新转出人资产信息
        $update_sql = "update {$db_prefix}users set jyprice = jyprice-{$money} where id = {$from_users['id']}";
        $res1 = $db->query($update_sql);
        if(!$res1){
            throw new Exception('转账失败');
        }
        if($type == 1){
            #交易钱包转出到对方的资产钱包
            $update_sql = "update {$db_prefix}users set price = price+{$money},ft_isend=0 where id = {$to_users['id']}";
            $res2 = $db->query($update_sql);
            if(!$res2){
                throw new Exception('转账失败');
            }
            #更新状态
            $result = $db->query("update {$db_prefix}transfer_account set status = 20 where id = {$insert_id}");
            if(!$result){
                throw new Exception('转账失败');
            }
            #写入财务记录
            hyepricejl($from_users['id'],"-{$money}",11,5,$curtime,"会员:{$from_users['username']}从交易钱包转出{$money}链到会员{$to_users['username']}的资产钱包");
            hyepricejl($to_users['id'],"{$money}",5,1,$curtime,"会员:{$to_users['username']}的资产钱包收到会员:{$from_users['username']}交易钱包转入的{$money}链");

            //请求交易接口
            $url = TXL_TRADE.'/user/Jsbackgroundapi/sysTransformation';
            $res = request_post($url,array('receive_men'=>$from_users['username'],'from_men'=>$to_users['username'],'trade_num'=>$money));
            $res = json_decode($res);
            if($res->code !=1){
                returnJson(0,$res->msg);
            }
            $db->query('commit');#提交
            returnJson(1,'转账成功');
        }else{
            throw new Exception('转账失败');            
        }
    }catch(Exception $e){
        $db->query('rollback');#回滚
        returnJson(0,$e->getMessage());
    }

}

